package com.troy.cardviews;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;

public class ListActivity extends AppCompatActivity {

    private ListView listView;
    private ArrayList<Bean> beans = new ArrayList<Bean>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        listView = (ListView) findViewById(R.id.listView);
        for (int i = 0; i < 10; i++) {
            Bean bean = new Bean();
            bean.setTitle("I am the " + i + " CardView ！");
            bean.setImgId(i%2==0?R.drawable.b:R.drawable.c);
            beans.add(bean);
        }
        listView.setAdapter(new ListViewAdapter(beans));
    }




    /*ListView适配器**/
    public class ListViewAdapter extends BaseAdapter {
        ArrayList<Bean> beans = new ArrayList<Bean>();

        public ListViewAdapter(ArrayList<Bean> beans) {
            this.beans = beans;
        }

        public int getCount() {
            return beans.size();
        }

        public Object getItem(int position) {
            return beans.get(position);
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder=null;
            LayoutInflater inflater = (LayoutInflater)ListActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            /*View复用*/
            if (convertView == null){
                convertView=inflater.inflate(R.layout.item_list, null);
                holder=new ViewHolder();
                // 通过findViewById()方法实例R.layout.item_list内各组件
                holder.text = (TextView) convertView.findViewById(R.id.title);
                holder.image = (ImageView) convertView.findViewById(R.id.img);
                convertView.setTag(holder);
            }
            holder=(ViewHolder)convertView.getTag();
            // 给holder中的控件进行赋值
            Bean bean=beans.get(position);
            holder.text.setText(bean.getTitle());
            holder.image.setImageResource(bean.getImgId());
            return convertView;
        }
    }

    class ViewHolder{
        ImageView image;
        TextView text;
    }
}
